<template>
  <div class="list-view">
    <div class="drawer drawer-animate" :class="{ 'is-open': drawer }">
      <div class="search">
        <div class="search-control">
          <span class="search-control-label">{{ $t("list.search.productName") }}</span>
          <FormControl
            class="search-control-form"
            v-model="search.productName"
            :placeholder="$t('list.search.productNamePlaceholder')"
            type="input"
            multiple
            clearable
          ></FormControl>
        </div>
        <div class="search-control">
          <span class="search-control-label">{{ $t("list.search.season") }}</span>
          <FormControl
            class="search-control-form"
            v-model="search.season"
            type="select"
            multiple
            clearable
            filterable
            :options="seasonOptions"
          ></FormControl>
        </div>
        <div class="search-control">
          <span class="search-control-label">{{ $t("list.search.productLine") }}</span>
          <FormControl
            class="search-control-form"
            v-model="search.productLine"
            type="select"
            multiple
            clearable
            filterable
            :options="productLineOptions"
          ></FormControl>
        </div>
        <!-- <div class="search-control">
        <span class="search-control-label">{{ $t("list.search.itemNo") }}</span>
        <FormControl
          class="search-control-form"
          v-model.trim="search.itemNo"
          type="input"
          clearable
          :placeholder="$t('list.search.itemNo')"
        ></FormControl>
      </div> -->
        <div class="search-control">
          <span class="search-control-label">{{ $t("list.search.meterial") }}</span>
          <FormControl
            class="search-control-form"
            v-model="search.meterial"
            type="select"
            multiple
            clearable
            filterable
            :options="meterialOptions"
          ></FormControl>
        </div>
        <div class="search-control">
          <span class="search-control-label">{{ $t("list.search.color") }}</span>
          <FormControl
            class="search-control-form"
            v-model="search.color"
            type="select"
            multiple
            clearable
            filterable
            :options="colorOptions"
          ></FormControl>
        </div>
        <div class="search-control">
          <span class="search-control-label">{{ $t("list.search.packingName") }}</span>
          <FormControl
            class="search-control-form"
            v-model="search.packingName"
            type="select"
            multiple
            clearable
            filterable
            :options="packgeOptions"
            :placeholder="$t('list.search.packingName')"
          ></FormControl>
        </div>
        <div class="search-control" v-if="role != 3">
          <span class="search-control-label">{{ $t("list.search.price") }}</span>
          <FormControl
            class="search-control-form"
            v-model.trim="search.priceMin"
            type="input"
            clearable
            :placeholder="$t('list.search.price')"
          ></FormControl>
          <span class="splitor">-</span>
          <FormControl
            class="search-control-form"
            v-model.trim="search.priceMax"
            type="input"
            clearable
            :placeholder="$t('list.search.price')"
          ></FormControl>
        </div>
        <el-divider></el-divider>
        <div class="btn-wrapper">
          <el-button type="danger" @click="handleSearch">{{ $t("list.search.search") }}</el-button>
          <el-button type="info" @click="handleReset">{{ $t("list.search.reset") }}</el-button>
          <!-- <el-button type="success">{{ $t("list.search.download") }}</el-button> -->
        </div>
        <el-button v-if="!isCustomer" @click="handleRedirect" class="btn-redirect" type="danger"
          >Manage Product</el-button
        >
        <el-button v-if="isCustomer" @click="logout" class="btn-redirect" type="danger"
          >logout</el-button
        >
      </div>
      <span class="toggle" @click="handleToggle">
        <i :class="'el-icon-d-arrow-' + (!drawer ? 'right' : 'left')"></i>
      </span>
    </div>
    <div class="list">
      <ul
        class="commodity"
        :class="{ 'is-open': drawer }"
        v-if="Array.isArray(newCommodityDatas) && newCommodityDatas.length > 0"
      >
        <li
          class="commodity-item"
          v-for="(item, idx) in newCommodityDatas"
          :key="item.id + '' + idx"
        >
          <div class="commodity-img">
            <img @click="handleDetail(item)" :src="item.cover" alt="failed to load resource" />
            <el-checkbox v-model="item.isCheck" class="commodity-info-check"></el-checkbox>
          </div>
          <div class="commodity-info">
            <span v-if="!isCustomer" class="commodity-info-price"
              >{{ $t("list.priceUnit") }}{{ item.price }}</span
            >
            <div class="commodity-info-name">{{ item.product_name }}</div>
          </div>
        </li>
      </ul>
      <Empty v-else :description="$t('list.empty')"></Empty>
      <div class="footer">
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[12, 24, 48, 96]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="searchDatas.length"
        >
        </el-pagination>
      </div>
    </div>
    <div class="btn-download" @click="handleDownload">
      <span class="el-icon-download"></span>
      <span>{{ downloading ? "loading..." : "download" }}</span>
    </div>
  </div>
</template>
<script>
import Vue from "vue";
import Component from "vue-class-component";
import { LocaleMixin } from "@/mixins/locale";
import { Empty } from "ant-design-vue";
import { getConfig, getProductList, download } from "@/api";
import { mapState } from "vuex";
import { isCustomer } from "@/config";
@Component({
  name: "ListView",
  mixins: [LocaleMixin],
  computed: {
    ...mapState({
      role: state => state.user.role,
      username: state => state.user.name
    })
  },
  components: {
    Empty
  }
})
export default class List extends Vue {
  drawer = false;

  commodityDatas = [];

  currentPage = 1;

  pageSize = 12;

  get isCustomer() {
    return isCustomer(this.role);
  }

  createEmptySearch() {
    return {
      productName: "",
      season: "",
      productLine: "",
      itemNo: "",
      meterial: "",
      color: "",
      packingName: "",
      priceMin: "",
      priceMax: ""
    };
  }

  search = this.createEmptySearch();

  seasonOptions = [];

  productLineOptions = [];

  packgeOptions = [];

  meterialOptions = [];

  colorOptions = [];

  newCommodityDatas = [];

  searchDatas = [];

  handleToggle() {
    this.drawer = !this.drawer;
  }

  handleRedirect() {
    this.$router.push({
      name: "GoodsManagement"
    });
  }
  logout() {
    localStorage.removeItem("Admin-Token");
    window.location.reload();
  }

  mounted() {
    this.getConfig();
  }

  created() {
    this.getList();
  }

  async getList() {
    let resp = await getProductList();
    if (resp && resp.code === 0) {
      this.commodityDatas = Object.freeze(resp.data);
      this.handleSearch();
    }
  }

  validInclude(seriesData, clientData) {
    if (clientData.length === 0) {
      return true;
    }
    return String(seriesData)
      .split(",")
      .find(x => clientData.some(d => d == x));
  }

  validProductName(str) {
    return (
      String(str)
        .toLowerCase()
        .indexOf(this.search.productName.toLowerCase()) >= 0
    );
  }

  handleReset() {
    Object.assign(this.search, this.createEmptySearch());
    this.searchDatas = this.commodityDatas[this.locale];
    this.setPageData();
  }

  handleSearch() {
    this.searchDatas = this.commodityDatas[this.locale]
      ? this.commodityDatas[this.locale].filter(item => {
          let {
            season,
            productLine,
            itemNo,
            meterial,
            color,
            packingName,
            priceMin,
            priceMax
          } = this.search;
          return (
            this.validProductName(item.product_name) &&
            this.validInclude(item.season, season) &&
            this.validInclude(item.product_line, productLine) &&
            this.validInclude(item.meterial, meterial) &&
            this.validInclude(item.color, color) &&
            this.validInclude(item.packing_name, packingName) &&
            (item.item_no === itemNo || itemNo === "") &&
            (+item.price >= priceMin || priceMin === "") &&
            (+item.price <= priceMax || priceMax === "")
          );
        })
      : [];
    this.setPageData();
  }

  setPageData() {
    this.newCommodityDatas = this.searchDatas.slice(
      (this.currentPage - 1) * this.pageSize,
      this.currentPage * this.pageSize
    );
  }

  handleSizeChange(val) {
    this.currentPage = 1;
    this.pageSize = val;
    this.setPageData();
  }

  handleCurrentChange(val) {
    this.currentPage = val;
    this.setPageData();
  }

  transform(o) {
    var locale = this.locale;
    return {
      value: o.id,
      label: locale === "zh-CN" ? o.ch : o.name
    };
  }

  handleDetail(row) {
    this.$router.push({
      name: "ProductDetail",
      query: {
        id: row.id
      }
    });
  }

  async getConfig() {
    let resp = await getConfig();
    if (resp && resp.code == 0) {
      var locale = this.locale;
      var data = resp.data[locale];
      this.seasonOptions = data.SEASON.map(this.transform);
      this.productLineOptions = data["PRODUCT LINE"].map(this.transform);
      this.meterialOptions = data["MATERIAL"].map(this.transform);
      this.colorOptions = data["COLOR"].map(this.transform);
      this.packgeOptions = data["PACKING NAME"].map(this.transform);
    }
  }

  downloading = false;

  async handleDownload() {
    var checkedList = this.newCommodityDatas.filter(x => x.isCheck);
    if (this.downloading) {
      return;
    }
    if (checkedList.length <= 0) {
      this.$message.error(this.$t("downloadMessage"));
      return;
    }
    this.downloading = true;
    try {
      let respStream = await download({
        id: checkedList.map(x => x.id).join(",")
      });
      console.log(respStream);
      const a = document.createElement("a");
      a.href = URL.createObjectURL(respStream);
      const date = new Date();
      a.download = date.format("yyyy-MM-dd") + "_" + this.username + "_" + "detailSheet.xlsx"; // 这里填保存成的文件名
      a.click();
      URL.revokeObjectURL(a.href);
      a.remove();
    } catch (ex) {
      console.log(ex);
    } finally {
      this.downloading = false;
    }
  }
}
</script>
<style lang="scss" scoped>
$bg: #f5f5f5;

.list-view {
  display: flex;
  background-color: $bg;
}

.drawer {
  width: 0px;
  height: 100vh;
  position: relative;
  background-color: $bg;
  &-animate {
    transition: all ease-in-out 0.3s;
  }

  .toggle {
    position: absolute;
    top: 50%;
    transform: translate(-50%, -50%);
    left: 10px;
    width: 25px;
    height: 100px;
    z-index: 1;
    cursor: pointer;
    background-color: #ff4949;
    border-top-right-radius: 15px;
    border-bottom-right-radius: 15px;
    display: flex;
    justify-content: center;
    align-items: center;
    color: white;
  }

  &.is-open {
    width: 330px;
    border-right: 1px solid #ccc;
    box-shadow: 0 0 10px #ccc;
    margin-right: 25px;
    .toggle {
      right: -39px;
      left: auto;
    }
    .search {
      visibility: visible;
    }
  }

  .search {
    display: flex;
    visibility: hidden;
    flex-direction: column;
    padding: 20px;
    .search-control {
      display: flex;
      width: 100%;
      align-items: center;
      &-label {
        width: 85px;
        text-align: right;
        margin-right: 20px;
        line-height: 60px;
      }
      &-form {
        flex: 1;
      }
    }

    .splitor {
      margin: 0 10px;
      color: black;
    }

    .el-button {
      height: 36px;
    }
  }

  .btn-wrapper {
    display: flex;
    justify-content: flex-end;
  }

  .btn-redirect {
    position: absolute;
    bottom: 20px;
    left: 50%;
    transform: translate(-50%, -50%);
  }
}

.btn-download {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: white;
  border-radius: 50%;
  position: fixed;
  bottom: 50px;
  right: 50px;
  width: 80px;
  height: 80px;
  padding: 45px;
  background: #ff4949;
  cursor: pointer;
  .el-icon-download {
    font-size: 26px;
  }
}

.list {
  flex: 1;
  height: 100vh;
  padding-top: 30px;
  overflow: auto;
  background-color: $bg;

  .commodity {
    margin: 0 auto;
    padding: 0;
    display: flex;
    flex-wrap: wrap;
    justify-content: flex-start;
    list-style-type: none;

    &-item {
      position: relative;
      margin-bottom: 25px;
      margin-right: 20px;
      padding-bottom: 120px;
      width: calc(20% - 20px);

      &:nth-child(5n) {
        margin-right: 0px;
      }
      border: 1px solid #ededed;
      background-color: white;
      box-sizing: border-box;
      .commodity-img {
        cursor: pointer;
        position: relative;
        img {
          width: 100%;
          height: 190px;
          object-fit: contain;
        }
      }

      .commodity-info-check {
        position: absolute;
        right: 10px;
        top: 10px;
      }

      .commodity-info {
        padding: 10px;
        position: absolute;
        width: 100%;
        bottom: 0;
        .free-mail {
          margin-left: 5px;
          padding: 2px;
          font-size: 12px;
          color: #fff;
          background: #f40;
        }
        &-price {
          color: #f40;
          font-weight: bold;
        }
        &-buy {
          float: right;
          color: #888;
          font-size: 12px;
        }
        &-name {
          margin-top: 10px;
          height: 45px;
          overflow: hidden;
          cursor: pointer;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;
        }
        &-check {
          float: right;
        }
      }
    }

    &.is-open {
      .commodity-item {
        width: calc(25% - 15px);
        &:nth-child(4n) {
          margin-right: 0px;
        }
        &:nth-child(5n) {
          margin-right: 20px;
        }
      }
    }
  }
  .commodity-item.empty {
    border: 0;
  }
  .footer {
    text-align: right;
    padding: 20px;
  }
}
</style>
